import token from '@/util/token'
import authority from '@/util/authority'
import Cookies from 'js-cookie'

var ajax_loading_count=0;

function parseQueryUrl(url){
    var url = url || window.location.href;
    //对非hash路由：为了防止误会：url所带参数中不要有：# , 因为location.hash是以#开始的。而且url中参数（？）和 hash（#）是有顺序的：先是 ？，后是 #
    //对hash路由，# 后面 ？有效
    //有三种情况：
    // 1. http://localhost:3003/manager?ctype=ykt#/teachercourselist?xxx=one
    // 2. http://localhost:3003/manager#/teachercourselist?xxx=one
    // 3. http://localhost:3003/manager?ctype=ykt#/teachercourselist
    var reg_url =/^[^\?]+\?([\w\W]+)$/,
        arr_url = reg_url.exec(url),
        reg_para=/([^&=]+)=([\w\W]*?)(&|$)/g, //g is very important
        ret = {};
    if(arr_url && arr_url[1]){
        if(url.indexOf("#") != -1){
            if(arr_url[1].indexOf("#") != -1){
                ret['hash'] = arr_url[1].substr(arr_url[1].indexOf("#")+1);
                arr_url[1] = arr_url[1].substring(0, arr_url[1].indexOf("#"));
            }else{
                ret['hash'] = url.substr(url.indexOf("#")+1).split("?")[0];
            }
            var hashQuery = reg_url.exec(ret['hash']);
            if(hashQuery && hashQuery[1]){
                var _str_para = hashQuery[1], _result;
                ret['hash'] = ret['hash'].split("?")[0];
                while((_result = reg_para.exec(_str_para)) != null){
                    ret[_result[1]] = _result[2];
                }
            }
        }
        var str_para = arr_url[1],result;
        while((result = reg_para.exec(str_para)) != null){
            ret[result[1]] = result[2];
        }
    }
    return ret;
}

function plugin(Vue) {
    if (Vue && Vue.http) {
        Vue.http.interceptors.push(function(request,next){
            var _xtbz = request.xtbz || "";
            request.headers.set('xtbz', _xtbz ? _xtbz : Cookies.get('platform_id') == 8 ? 'training' : 'cloud'); //业务线表示xt:新主站， ykt：雨课堂，aaoto：清华校友，cloud:学堂云4, jsmh: 京师慕华（stduio数据看板）,training:培训平台
            request.headers.set('university-id', Cookies.get('university_id')); //将cookie中的university_id放入header中
            request.headers.set('platform-id', Cookies.get('platform_id') || 0);

            if (request.method === 'GET') {
                if (request.get_array && process.env.NODE_ENV == 'production'){
                    var sUrl = "";
                    for(var i=0;i<request.get_array.length;i++){
                        sUrl += request.get_array[i] +"/";
                    }
                    if (sUrl!== ""){
                        request.url += sUrl;
                    }
                }
                request.query = request.query || {}
                if(request.query){
                    var sQuery = "", isFirst = true;
                    for(var key in request.query){
                        if (request.query[key] !== undefined){
                            if(isFirst){
                                isFirst = false;
                                sQuery += key + "=" + request.query[key];
                            }else{
                                sQuery += "&" + key + "=" + request.query[key];
                            }
                        }
                    }
                    if (sQuery!== ""){
                        request.url += (request.url.indexOf('?')>=0? '&':"?") + sQuery;
                    }
                }
            }
            
            if (request.method === 'POST' || request.method === 'PATCH' || request.method === 'DELETE' || request.method === 'PUT' || process.env.NODE_ENV !== 'production') {
                request.headers.set('X-CSRFToken', token());
            }
            if (request.url.indexOf("?")>-1){
                request.url = request.url + "&_date="+(new Date()).valueOf();
            }else{
                request.url = request.url + "?_date="+(new Date()).valueOf();
            }
            let termStr = localStorage.getItem('currentTerm')
            let termObj =  termStr ? JSON.parse(termStr) : null
            let term = termObj ? termObj.value : 'latest'

            if (!(request.query && request.query.term)) {
                request.url = request.url + "&term=" + term;
            }
            
            if (!request.no_loading){
                $("#global_loading").removeClass("hide");
            }else{
                $("#global_loading").addClass("hide");
            }
            
            ajax_loading_count++;
            next(function(response){
                authority.hasRight(response);
                ajax_loading_count--;
                if(ajax_loading_count<=0){
                    ajax_loading_count = 0;
                    setTimeout(function(){
                        //延迟1秒消失，等待界面渲染数据完成
                        $("#global_loading").addClass("hide");
                    },1000);
                }
            });
        });
    }
}

export default plugin
